#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"
#include "LockGuard.hpp"
using namespace LOGSpace;

using task_t = std::function<void()>;
class Route
{
public:
    Route()
    {
        pthread_mutex_init(&_mutex, nullptr);
    }
    void CheckOnlineUser(InetAddr &who)
    {
        for (auto &user : _online_users)
        {
            if (user == who)
            {
                LOG(DEBUG, "用户[%s:%d]已添加,无需再次添加! \n", who.Ip().c_str(), who.Port());
                return;
            }
        }

        _online_users.push_back(who);
        LOG(INFO, "用户[%s:%d]已上线!\n", who.Ip().c_str(), who.Port());
    }
    void OffOnlineUser(InetAddr &who)
    {
        LockGuard lock(&_mutex);
        auto it = _online_users.begin();
        while (it != _online_users.end())
        {
            if (*it == who)
            {
                _online_users.erase(it);
                printf("[%s:%d]已离线! \n", who.Ip().c_str(), who.Port());
                // 立即退出，防止迭代器失效问题
                break;
            }
            ++it;
        }
    }
    void ForwardHelper(int sockfd, std::string message, InetAddr who)
    {
        LockGuard lock(&_mutex);
        std::string message_client = who.GetAddrStr() + message;
        for (auto &user : _online_users)
        {
            struct sockaddr_in addr = user.GetSockaddr();
            ssize_t n = ::sendto(sockfd, message_client.c_str(), message_client.size(), 0, (struct sockaddr *)&addr, sizeof(addr));
            if (n < 0)
                LOG(ERROR, "send message error!\n");
        }
    }
    // 转发
    void Forward(int sockfd, const std::string &message, InetAddr &who)
    {
        // 1.添加用户到在线列表，如果用户不在则添加
        CheckOnlineUser(who);
        task_t t;
        // 1.2下线用户
        if (message == "QUIT" || message == "q")
        {
            OffOnlineUser(who);
            std::string QuitMsg;
            QuitMsg = who.GetAddrStr() + "quit done!!! \n";
            t = std::bind(&Route::ForwardHelper, this, sockfd, QuitMsg, who);
        }
        else
        {
            t = std::bind(&Route::ForwardHelper, this, sockfd, message, who);
        }
        // 2.群发信息--线程池
        ThreadPool<task_t>::GetThreadPoolInstance()->Push(t);
    }
    ~Route()
    {
        pthread_mutex_destroy(&_mutex);
    }

private:
    std::vector<InetAddr> _online_users; // 在线用户列表
    pthread_mutex_t _mutex;
};
